﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Services;
using DataModels.Models;
using DataModels.Models.Messaging;
using GenericTools;
using DataModels.Models.Context;

namespace IQWebServices
{
    /// <summary>
    /// Summary description for IQMessaging
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class IQMessaging : System.Web.Services.WebService
    {
        private const string TANZANIA_COUNTRY_CODE = "+255";
        public enum MessageRequestType
        {
            RECEIVED_BY_USER = 1,
            SEND_BY_USER = 2,
            ALL_MESSAGES = 3
        };

        static IQMessaging()
        {
            string connectionName = "IQSMS_TestDBContext";
            AppConfiguration.DBConnectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            AppConfiguration.DBProviderName = ConfigurationManager.ConnectionStrings[connectionName].ProviderName;

            AppConfiguration.ApplicationName = Properties.Settings.Default.ApplicationName;
            AppConfiguration.EnableErrorLogMail = Properties.Settings.Default.EnableErrorLogMail;
            AppConfiguration.ErrorLogEmailAddress = Properties.Settings.Default.ErrorLogEmailAddress;
            AppConfiguration.LogFileDirectory = Properties.Settings.Default.LogFileDirectory;

            AppConfiguration.MailFrom = Properties.Settings.Default.MailFrom;
            AppConfiguration.MailPassword = Properties.Settings.Default.MailPassword;
            AppConfiguration.MailServer = Properties.Settings.Default.MailServer;
            AppConfiguration.MailServerPort = Properties.Settings.Default.MailServerPort;
            AppConfiguration.MailUsername = Properties.Settings.Default.MailUsername;

            AppConfiguration.MaximumErrorTolerance = Properties.Settings.Default.MaxErrorCount;
            AppConfiguration.MaximumReportDelay = Properties.Settings.Default.MaximumReportDelay;

            AppConfiguration.OfflineDataCacheLifetime = Properties.Settings.Default.OfflineDataCacheLifetime;
            AppConfiguration.AccessMethod = DataModels.Enumerations.DataAccessMethod.DIRECT_ACCESS;
            //AppConfiguration.DataCached = Properties.Settings.Default.DataCached;
            //AppConfiguration.WebServiceURL = Properties.Settings.Default.WeServiceURL;

            //connectionName = "IQWebServices.Properties.Settings.CacheDBConnection";
            //AppConfiguration.CacheDBProviderName = ConfigurationManager.ConnectionStrings[connectionName].ProviderName;
            //AppConfiguration.CacheDBConnectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;

            //AppConfiguration.SSISPackageFilename = Properties.Settings.Default.SSISPackageFilename;
            //AppConfiguration.SourceConnectionStringForPackage = Properties.Settings.Default.SourceConnectionStringForPackage;
            //AppConfiguration.DestinationConnectionStringForPackage = Properties.Settings.Default.DestinationConnectionStringForPackage;
        }

        private bool QueueingMessage(string phoneNumber, string message)
        {
            if (string.IsNullOrWhiteSpace(phoneNumber)) throw new Exception("Phone number is missing");
            if (string.IsNullOrWhiteSpace(message)) throw new Exception("Message content is missing");

            if (phoneNumber.StartsWith(TANZANIA_COUNTRY_CODE))
            {
                using (var db = new IQSMS_TestDBContext())
                {
                    var queue = new SendSMSQueue
                    {
                        SenderNum = phoneNumber,
                        TxtDetails = message
                    };

                    var userPhoneNumber = new OtherSystemUserNumber { PhoneNumber = phoneNumber };
                    var log = new MessagingLog
                    {
                        DateSendReceived = DateTime.Now,
                        IsMessageSentToUser = true,
                        MessageBody = message,
                        PhoneNumber = phoneNumber,
                    };

                    bool numberDontExists = (from n in db.OtherSystemUserNumbers
                                             where n.PhoneNumber == phoneNumber
                                             select n).Count() == 0;
                    if (numberDontExists) db.OtherSystemUserNumbers.Add(userPhoneNumber);
                    
                    db.SendSMSQueues.Add(queue);
                    db.OtherSystemMessagingLogs.Add(log);
                    db.SaveChanges();
                    return true;
                }
            }
            else return false;
        }

        [WebMethod]
        public bool SendMessage(string phoneNumber, string message)
        {
            return QueueingMessage(phoneNumber, message);
        }

        [WebMethod]
        public List<bool> SendMessages(List<string> phoneNumbers, string message)
        {
            List<bool> status = new List<bool>();
            foreach (var phoneNumber in phoneNumbers)
            {
                bool s = QueueingMessage(phoneNumber, message);
                status.Add(s);
            }
            return status;
        }

        [WebMethod]
        public List<bool> SendSeveralMessages(List<string> phoneNumbers, List<string> messages)
        {
            if (phoneNumbers.Count != messages.Count) throw new Exception("Inconsistent phone-message pair");
            
            for (int i = 0; i < phoneNumbers.Count; i++) 
            {
                var phoneNumber = phoneNumbers[i];
                if (string.IsNullOrWhiteSpace(phoneNumber)) throw new Exception("Phone number is missing in index-" + i);
            }

            for (int i = 0; i < messages.Count; i++)
            {
                var message = messages[i];
                if (string.IsNullOrWhiteSpace(message)) throw new Exception("Message content is missing in index-" + i);
            }

            List<bool> status = new List<bool>();
            for (int i = 0; i < phoneNumbers.Count; i++)
            {
                var phoneNumber = phoneNumbers[i];
                var message = messages[i];
                bool s = QueueingMessage(phoneNumber, message);
                status.Add(s);
            }
            return status;
        }
        
        [WebMethod]
        public List<MessagingLog> GetMessageLog(string phoneNumber, MessageRequestType type, DateTime startDate, DateTime endDate)
        {
            List<MessagingLog> results = new List<MessagingLog>();
            using (var db = new IQSMS_TestDBContext())
            {
                db.Configuration.LazyLoadingEnabled = false;
                db.Configuration.ProxyCreationEnabled = false;
                switch (type)
                {
                    case MessageRequestType.ALL_MESSAGES:
                        var all = from a in db.OtherSystemMessagingLogs
                                  where a.PhoneNumber == phoneNumber
                                  && a.DateSendReceived >= startDate
                                  && a.DateSendReceived <= endDate
                                  select a;
                        if (all != null) results = all.ToList();
                        break;

                    case MessageRequestType.RECEIVED_BY_USER:
                        var receivedByUser = from a in db.OtherSystemMessagingLogs
                                             where a.PhoneNumber == phoneNumber
                                             && a.IsMessageSentToUser == true
                                             && a.DateSendReceived >= startDate
                                             && a.DateSendReceived <= endDate
                                             select a;
                        if (receivedByUser != null) results = receivedByUser.ToList();
                        break;

                    case MessageRequestType.SEND_BY_USER:
                        var sendByUser = from a in db.OtherSystemMessagingLogs
                                         where a.PhoneNumber == phoneNumber
                                         && a.IsMessageSentToUser == false
                                         && a.DateSendReceived >= startDate
                                         && a.DateSendReceived <= endDate
                                         select a;
                        if (sendByUser != null) results = sendByUser.ToList();
                        break;
                }
            }

            return results;
        }

        [WebMethod]
        public List<MessagingLog> GetAllMessageLog(MessageRequestType type, DateTime startDate, DateTime endDate)
        {
            List<MessagingLog> results = new List<MessagingLog>();
            using (var db = new IQSMS_TestDBContext())
            {
                db.Configuration.LazyLoadingEnabled = false;
                db.Configuration.ProxyCreationEnabled = false;
                switch (type)
                {
                    case MessageRequestType.ALL_MESSAGES:
                        var all = from a in db.OtherSystemMessagingLogs
                                  where a.DateSendReceived >= startDate
                                  && a.DateSendReceived <= endDate
                                  select a;
                        if (all != null) results = all.ToList();
                        break;

                    case MessageRequestType.RECEIVED_BY_USER:
                        var receivedByUser = from a in db.OtherSystemMessagingLogs
                                             where a.IsMessageSentToUser == true
                                             && a.DateSendReceived >= startDate
                                             && a.DateSendReceived <= endDate
                                             select a;
                        if (receivedByUser != null) results = receivedByUser.ToList();
                        break;

                    case MessageRequestType.SEND_BY_USER:
                        var sendByUser = from a in db.OtherSystemMessagingLogs
                                         where a.IsMessageSentToUser == false
                                         && a.DateSendReceived >= startDate
                                         && a.DateSendReceived <= endDate
                                         select a;
                        if (sendByUser != null) results = sendByUser.ToList();
                        break;
                }
            }

            return results;
        }
    }
}
